package com.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author: lvjun
 * @date: 2019-11-19 14:38
 * @文件说明：
 */
public class HttpUtils {

    private HttpUtils() {
    }

    private final static String ENCODE = "UTF-8";

    /**
     * 发送HttpPost请求
     *
     * @param url    请求地址
     * @param body   消息体
     * @param header 消息头
     * @return 响应
     * @throws Exception
     * @throws ClientProtocolException
     */
    public static String post(String url, String body, Map<String, String> header)
            throws ClientProtocolException, Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(body, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        entity.setContentType("text/xml");
        post.setEntity(entity);
        if (header != null && !header.isEmpty()) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                String k = entry.getKey();
                String v = entry.getValue();
                post.setHeader(k, v);
            }
        }
        HttpResponse httpResponse = httpClient.execute(post);
        String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        post.releaseConnection();
        return response;
    }



    /**
     * 发送HttpPost请求
     *
     * @param url    请求地址
     * @param body   消息体
     * @return 响应
     * @throws Exception
     * @throws ClientProtocolException
     */
    public static String post(String url, String body)
            throws ClientProtocolException, Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(body, Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        entity.setContentType("text/xml");
        post.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(post);
        String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        post.releaseConnection();
        return response;
    }

}
